package com.tianyadu.order.service.impl;

import com.tianyadu.order.domain.OrderDetail;
import com.tianyadu.order.domain.OrderMaster;
import com.tianyadu.order.dto.OrderDTO;
import com.tianyadu.order.enums.OrderStatusEnum;
import com.tianyadu.order.enums.PayStatusEnum;
import com.tianyadu.order.enums.ResultEnum;
import com.tianyadu.order.exception.OrderException;
import com.tianyadu.order.repository.OrderDetailRepository;
import com.tianyadu.order.repository.OrderMasterRepository;
import com.tianyadu.order.service.OrderService;
import com.tianyadu.order.utils.KeyUtil;
import com.tianyadu.product.client.ProductClient;
import com.tianyadu.product.common.DecreaseStockInput;
import com.tianyadu.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.service.spi.InjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @FileName: OrderServiceImpl
 * @Description:
 * @author: xueyj
 * @create: 2018-07-02 22:13
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
     private OrderMasterRepository orderMasterRepository;

    @Autowired
     private OrderDetailRepository orderDetailRepository;

    @Autowired
    private ProductClient productClient;


    /**
     * 1. 参数检验
     * 2. 查询商品信息(调用商品服务)
     * 3. 计算总价
     * 4. 扣库存(调用商品服务)
     * 5. 订单入库
     */
    @Override
    public OrderDTO creatOrder(OrderDTO orderDTO) {
        String orderId = KeyUtil.genUniqueKey();
        //  获取商品id信息
        List<String> productIdList = orderDTO.getOrderDetailList()
                .stream()
                .map(OrderDetail::getProductId)
                .collect(Collectors.toList());
        //  调用product服务，查询商品信息
        List<ProductInfoOutput> productInfoList = productClient.listForOrder(productIdList);

        //  计算总价
        BigDecimal orderAmout = new BigDecimal(BigInteger.ZERO);
        //  单价*数量
        for (OrderDetail orderDetailItem : orderDTO.getOrderDetailList()) {
            for (ProductInfoOutput productInfoItem : productInfoList) {
                //  校验订单详情中商品id是否已商品详细id匹配
                if (!productInfoItem.getProductId().equals(orderDetailItem.getProductId())){
                    continue;
                }
                orderAmout = productInfoItem.getProductPrice()
                        .multiply(new BigDecimal(orderDetailItem.getProductQuantity()))
                        .add(orderAmout);

                //  将商品信息复制到商品详情中
                BeanUtils.copyProperties(productInfoItem,orderDetailItem);
                orderDetailItem.setOrderId(orderId);
                orderDetailItem.setDetailId(KeyUtil.genUniqueKey());
                //  订单详情入库
               orderDetailRepository.save(orderDetailItem);
            }
        }

        //  调用商品服务扣库存
        List<DecreaseStockInput> decreaseStockInputList = orderDTO.getOrderDetailList()
                .stream()
                .map(e -> new DecreaseStockInput(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productClient.decreaseStock(decreaseStockInputList);

        //  订单入库
        OrderMaster orderMaster = new OrderMaster();
        //  设置订单id
        orderDTO.setOrderId(orderId);
        //  copy orderDTO对象属性到orderMaster
        BeanUtils.copyProperties(orderDTO, orderMaster);
        //  订单总金额
        orderMaster.setOrderAmount(orderAmout);
        //  订单状态
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        //  订单支付状态
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterRepository.save(orderMaster);
        return orderDTO;
    }

    /**
      * @Description: 订单完结
      * @param:
      * @return:
      * @author:
      * @date:   2018/11/23 17:24
      */
    @Override
    @Transactional
    public OrderDTO finish(String orderId) {
        //1. 先查询订单
        Optional<OrderMaster> orderMasterOptional = orderMasterRepository.findById(orderId);
        if (!orderMasterOptional.isPresent()) {
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }

        //2. 判断订单状态
        OrderMaster orderMaster = orderMasterOptional.get();
        if (OrderStatusEnum.NEW.getCode().equals(orderMaster.getOrderStatus())) {
            throw new OrderException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //3. 修改订单状态为完结
        orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        orderMasterRepository.save(orderMaster);

        //查询订单详情
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new OrderException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }

    /**
     * @Description: 根据订单id查询订单详情list
     * @param:
     * @return:
     * @author:
     * @date:   2018/11/23 23:51
     */
    @Override
    public List<OrderDetail> findOrdersByOrderId(String orderId) {
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        return orderDetailList;
    }
}